// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#pragma once

#include <memory>
#include <string>
#include <thread>

#include <melon/socket_address.h>
#include <melon/synchronization/call_once.h>

namespace apache::thrift {
    class ThriftServer;
} // namespace apache::thrift

namespace kumo::pollux::functions {
    constexpr std::string_view kRemoteFunctionPrefix = "remote";

    struct RemoteFunctionServiceParams {
        // Function prefix to be used for registering the actual functions.
        // This is needed when server is running in the same process.
        std::string functionPrefix;

        // The socket address that the thrift server is running on.
        melon::SocketAddress serverAddress;
    };

    class IRemoteFunctionServiceProvider {
    public:
        virtual ~IRemoteFunctionServiceProvider() = default;

        virtual RemoteFunctionServiceParams getRemoteFunctionServiceParams() = 0;
    };

    class RemoteFunctionServiceProviderForLocalThrift
            : public IRemoteFunctionServiceProvider {
    public:
        // Creates a thrift server that runs in a separate thread
        // and returns the parameters of the service.
        RemoteFunctionServiceParams getRemoteFunctionServiceParams() override;

        ~RemoteFunctionServiceProviderForLocalThrift() override;

    private:
        void initializeServer();

        // Loop until the server is up and running.
        bool waitForRunning();

        std::shared_ptr<apache::thrift::ThriftServer> server_;
        std::unique_ptr<std::thread> thread_;

        // Creates a random temporary file name to use to communicate as a unix domain
        // socket.
        melon::SocketAddress location_ = []() {
            char name[] = "/tmp/socketXXXXXX";
            int fd = mkstemp(name);
            if (fd < 0) {
                throw std::runtime_error("Failed to create temporary file for socket");
            }
            close(fd);
            std::string socketPath(name);
            // Cleanup existing socket file if it exists.
            unlink(socketPath.c_str());
            return melon::SocketAddress::makeFromPath(socketPath);
        }();

        const std::string remotePrefix_{kRemoteFunctionPrefix};
        melon::once_flag initializeServiceFlag_;
    };

    // If no thrift server is currently running, creates a thrift server
    // that runs in a separate thread and returns the parameters of the service.
    // If a thrift server is already running, returns the parameters of the service.
    RemoteFunctionServiceParams startLocalThriftServiceAndGetParams();
} // namespace kumo::pollux::functions
